home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2006 May / PCWMAY06.iso / Software / Freeware / First Page 2006 3.00 / fp2006-final-3.00-setup.exe / {app} / Iscripts / Maths & Calculations / round-number-to-x-decimals.izs < prev    next >
Text File  |  2005-07-29  |  1KB  |  58 lines

  1. <!NOWIZARD>
  2.  
  3. <!TITLE>Round number to x decimals
  4. <!/TITLE>
  5.  
  6. <!DESCRIPTION>A useful utility that rounds any number to the specified decimal place. This is needed because JavaScript doesn't have any built-in methods for the task. The function takes two parameters- a number (has to be a number datatype), and the number of places to round it to.
  7. <!/DESCRIPTION> 
  8.  
  9. <!CATEGORY>math related<!/CATEGORY>
  10.  
  11. <!SCRIPT>
  12. <!-- START OF SCRIPT -->
  13. <script>
  14.  
  15. function roundit(Num, Places) {
  16.    if (Places > 0) {
  17.       if ((Num.toString().length - Num.toString().lastIndexOf('.')) > (Places + 1)) {
  18.          var Rounder = Math.pow(10, Places);
  19.          return Math.round(Num * Rounder) / Rounder;
  20.       }
  21.       else return Num;
  22.    }
  23.    else return Math.round(Num);
  24. }
  25.  
  26. //Sample usage- This will round 23.3353 to 2 decimals and then alert result:
  27. alert(roundit(23.3353, 2))
  28. </script>
  29.  
  30.  
  31. <!-- END OF SCRIPT -->
  32. <!/SCRIPT>
  33.  
  34. <!PREVIEW>
  35. <!-- START OF SCRIPT -->
  36. <script>
  37.  
  38. function roundit(Num, Places) {
  39.    if (Places > 0) {
  40.       if ((Num.toString().length - Num.toString().lastIndexOf('.')) > (Places + 1)) {
  41.          var Rounder = Math.pow(10, Places);
  42.          return Math.round(Num * Rounder) / Rounder;
  43.       }
  44.       else return Num;
  45.    }
  46.    else return Math.round(Num);
  47. }
  48.  
  49. //Sample usage- This will round 23.3353 to 2 decimals and then alert result:
  50. alert(roundit(23.3353, 2))
  51. </script>
  52.  
  53.  
  54.  
  55. <!-- END OF SCRIPT -->
  56. <!/PREVIEW>
  57.  
  58. <!RELATED>NONE<!/RELATED>